package net.oschina.jhssm.module.system.service.impl;

import net.oschina.jhssm.common.service.impl.BaseServiceImpl;
import net.oschina.jhssm.module.system.SystemConst;
import net.oschina.jhssm.module.system.dao.SysResourceMapper;
import net.oschina.jhssm.module.system.dto.NavTreeNode;
import net.oschina.jhssm.module.system.entity.SysResource;
import net.oschina.jhssm.module.system.service.ISysResourceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaojb on 2017/8/20.
 */
@Service
public class SysResourceServiceImpl extends BaseServiceImpl<SysResource> implements ISysResourceService {

    private SysResourceMapper sysResourceMapper;

    @Autowired
    public SysResourceServiceImpl(SysResourceMapper sysResourceMapper) {
        super.baseMapper = sysResourceMapper;
        this.sysResourceMapper = sysResourceMapper;
    }

    private List<NavTreeNode> findNavTreeNodeByParentId(String parentId) {
        List<NavTreeNode> navTreeNodeList = new ArrayList<>();
        Subject subject = SecurityUtils.getSubject();

        SysResource sysResourceQuery = new SysResource();
        sysResourceQuery.setParentId(parentId);
        sysResourceQuery.setIsEnable(true);
        List<SysResource> sysResources = sysResourceMapper.select(sysResourceQuery);
        for (SysResource sysResource : sysResources) {
            String permission = sysResource.getPermission();
            if (StringUtils.isEmpty(permission) || subject.isPermitted(permission)) {

                NavTreeNode navTreeNode = new NavTreeNode();
                navTreeNode.setTitle(sysResource.getName());
                navTreeNode.setIcon(sysResource.getIcon());
                navTreeNode.setType(sysResource.getType());
                navTreeNode.setAction(sysResource.getAction());

                navTreeNode.setChildren(findNavTreeNodeByParentId(sysResource.getId()));
                navTreeNodeList.add(navTreeNode);
            }
        }

        return navTreeNodeList;
    }

    @Override
    public List<NavTreeNode> createNavTreeView() {
        return findNavTreeNodeByParentId(SystemConst.sysResourceRootId);
    }
}
